package edit;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import pulpcore.sprite.Sprite;
import pulpcore.Input;
import draw.DrawCircleSprite;
import draw.DrawPolygonSprite;
import pulpfizz.physics.BodyUtils;
import pulpfizz.physics.Material;
import pulpfizz.pulp.body.Java2DBodySprite;

import java.util.ArrayList;
import java.util.List;
import java.awt.*;

import goliath.BasicDemo;

/**
 * Draw Polygon: Click once for each point, then double click to complete
 *
 * @author will
 * @date Aug 9, 2008 10:09:24 PM
 */
public class DrawPolygonContext extends EditContext {

    Vec2 startPos;
    Sprite drawSprite;
    public List<Vec2> points;

    public DrawPolygonContext() {
        super();
        startPos = new Vec2();
        points = new ArrayList<Vec2>();
    }

    public void update(int elapsedTime) {

        if(Input.isPressed(Input.KEY_DOUBLE_MOUSE_BUTTON_1)) {
            System.out.println("Double mouse!");
            // Double click = complete polygon, if we have enough vertices

            // Remove outline and clear the vertices
            layer.remove(drawSprite);

            if(points.size() >= 3) {
                Body polygon = BodyUtils.createPolygon(layer.getWorld(), points.toArray(new Vec2[points.size()]));
                if(polygon!=null) {
                    if(!BasicDemo.isFixed()) {
                        Material.DEAD_WEIGHT().applyAll(polygon);
                    }
                    Java2DBodySprite bs = new Java2DBodySprite(polygon, layer, 2, BasicDemo.getDrawColor(), BasicDemo.getFillColor());
                    layer.add(bs);
                }
            }

            points.clear();
        } else if (Input.isMousePressed()) {
            if(points.isEmpty()) {
                // Create a new draw sprite if this is the first point
                drawSprite = new DrawPolygonSprite(this);
                layer.add(drawSprite);
            }

            // Add the new point to the vector
            points.add(mousePos.clone());
        }

        if (Input.isMouseReleased()) {

        }

    }

    public void reset() {
        startPos.setZero();
        points.clear();
    }

    public String toString() {
        return "Polygon";
    }


}
